package com.ruoyi.web.core.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.erhlc.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchCustomConversions;
import java.util.Arrays;

/**
 * elasticsearch的接口配置
 *
 * @author weixingyu
 */
@Configuration
public class ElasticsearchConfig {

    // host
    @Value("${spring.elasticsearch.rest.host}")
    private String host;

    // 端口
    @Value("${spring.elasticsearch.rest.port}")
    private int port;

    // 用户名
    @Value("${spring.elasticsearch.rest.username}")
    private String username;

    // 密码
    @Value("${spring.elasticsearch.rest.password}")
    private String password;

    @Bean
    public ElasticsearchCustomConversions elasticsearchCustomConversions() {
        return new ElasticsearchCustomConversions(
                Arrays.asList(new UtcToGmt8Converter())
        );
    }

    @Bean
    public RestHighLevelClient client() {

        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(
                AuthScope.ANY,
                new UsernamePasswordCredentials(username, password)
        );
        RestClientBuilder builder = RestClient.builder(new HttpHost(host, port))
                .setHttpClientConfigCallback(httpClientBuilder -> {
                    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    // 添加兼容性头
                    httpClientBuilder.setDefaultHeaders(
                            Arrays.asList(
                                    new BasicHeader("Accept", "application/vnd.elasticsearch+json;compatible-with=7"),
                                    new BasicHeader("Content-Type", "application/vnd.elasticsearch+json;compatible-with=7")
                            )
                    );
                    return httpClientBuilder;
                });

        return new RestHighLevelClient(builder);
    }
    @Bean
    public ElasticsearchRestTemplate elasticsearchTemplate(RestHighLevelClient client) {
        return new ElasticsearchRestTemplate(client);
    }


}